package cn.j0n4than.api.controller.api.auth;

import cn.j0n4than.api.config.ResponseConfig;
import cn.j0n4than.api.entity.Auth;
import cn.j0n4than.api.entity.User;
import cn.j0n4than.api.entity.pojo.UserAddPojo;
import cn.j0n4than.api.entity.pojo.UserLoginPojo;
import cn.j0n4than.api.utils.BcryptUtil;
import cn.j0n4than.api.utils.Response;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author jonathan
 * <p>
 * 用户授权控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth/user")
public class AuthUserController extends AuthBaseController {

    /**
     * 用户登陆
     *
     * @param userLoginPojo 登陆字段类
     * @return Response
     */
    @PostMapping("login")
    public Response login(@Validated @RequestBody UserLoginPojo userLoginPojo, BindingResult validateResult, HttpServletRequest request) {
        Response response = Response.response();

        //获取验证器错误
        if (validateResult.hasErrors()) {
            assert validateResult.getFieldError() != null;
            String message = validateResult.getFieldError().getDefaultMessage();
            return response.setStatus(ResponseConfig.ERROR).setMessage(message);
        }

        User user = userService.login(userLoginPojo.username, userLoginPojo.password);
        if (user != null) {
            try {
                Auth auth = new Auth();
                auth.userId = user.id;
                auth.ip = request.getRemoteAddr();
                //设置token过期时间
                auth.expire = new Date((new Date()).getTime() + 3600000 * 24);
                auth.type = Auth.TYPE_USER;
                String json = objectMapper.writeValueAsString(auth);
                //加密token
                String token = desUtil.encrypt(json);

                //不返回密码
                user.password = null;

                //更新登陆信息
                user.lastLoginAt = new Date(System.currentTimeMillis());
                user.lastLoginIp = request.getRemoteAddr();
                userService.update(user.id, user);

                response.setStatus(ResponseConfig.SUCCESS)
                        .setMessage("登陆成功")
                        .setResult("user", user)
                        .setResult("token", token);
            } catch (JsonProcessingException e) {
                response.setStatus(ResponseConfig.ERROR)
                        .setMessage("用户名或密码错误");

                log.error("加密Token失败");
                log.error(e.getMessage());
            }
        } else {
            response.setStatus(ResponseConfig.ERROR)
                    .setMessage("用户名或密码错误");
        }

        return response;
    }

    /**
     * 用户注册
     *
     * @param userAddPojo 用户添加字段类
     * @return Response
     */
    @PostMapping("/reg")
    public Response reg(@RequestBody UserAddPojo userAddPojo) {
        Response response = Response.response();
        User user = new User();
        user.username = userAddPojo.username;
        user.password = BcryptUtil.passwordHash(userAddPojo.password);
        user.email = userAddPojo.email;

        if (userService.insert(user) > 0) {
            response.setStatus(200).setMessage("注册成功");
        } else {
            response.setStatus(500).setStatus(500).setMessage("注册失败");
        }

        return response;
    }

}
